<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col v-if="!hasPointFlag" :span="24">
            <a-form-model-item label="区域" :labelCol="rowLabelCol" :wrapperCol="rowWrapperCol" prop="pointArea">
              <j-select-depart placeholder="请选择" v-model="model.pointArea" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equName">
              <a-input v-model="model.equName" placeholder="请输入设备名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equNo">
              <a-input v-model="model.equNo" placeholder="请输入设备编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="SIM卡号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-model="model.sim" placeholder="请输入SIM卡号" style="width: 100%"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="安装时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.installTime" placeholder="请输入安装时间" ></a-input>
            </a-form-model-item>
          </a-col>
          <template v-if="hasPointFlag">
            <a-col :span="24">
              <a-form-model-item label="点位名称" :labelCol="rowLabelCol" :wrapperCol="rowWrapperCol">
                <a-select
                  :showArrow="false"
                  :showSearch="true"
                  v-model="value"
                  placeholder="请输入点位名称"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? undefined : null"
                  @search="fetchPointsList"
                  @change="handleChange"
                  @focus="fetchPointsList"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="d in data" :key="d.pointNo" :value="d.pointNo">
                    {{ d.pointName }} ({{ d.pointNo }})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="点位编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="model.pointCode" type="number" :disabled="true"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="管点编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipPointNo">
                <a-input v-model="model.pipPointNo" type="string" :disabled="true"></a-input>
              </a-form-model-item>
            </a-col>
          </template>
          <template v-if="!hasPointFlag && !model.id">
            <a-col :span="12">
              <a-form-model-item label="经度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="longitude">
                <a-input-number v-model="model.longitude" placeholder="请输入经度" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="纬度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="latitude">
                <a-input-number v-model="model.latitude" placeholder="请输入纬度" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="安装点类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipType">
                <a-select v-model="model.installType">
                  <a-select-option :value="1">雨水井</a-select-option>
                  <a-select-option :value="2">污水井</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="安装点编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="model.installNo" placeholder="自动生成" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="道路" :labelCol="rowLabelCol" :wrapperCol="rowWrapperCol">
                <a-input v-model="model.street" placeholder="请输入道路"></a-input>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :span="12">
            <a-form-model-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equType">
              <JDictSelectTag v-model="model.equType" dictCode="ps_equ_type" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="补偿值" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.compensate" placeholder="请输入补偿值" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联农污终端" :labelCol="rowLabelCol" :wrapperCol="rowWrapperCol">
              <!-- <a-input v-model="model.terminalId" placeholder="关联农污终端检索选择" type="number"></a-input> -->
              <a-select
                v-model="model.terminalId"
                show-search
                allowClear
                placeholder="请选择"
                :default-active-first-option="false"
                :show-arrow="false"
                :not-found-content="null"
                option-filter-prop="children"
                @change="handleTerminalSelected"
              >
                <!-- 显示终端名称+编号 -->
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="item in terminalList" :key="item.value" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="终端组成设施" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                v-model="model.facilityNo"
                show-search
                placeholder="请选择"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in facilityList" :key="item.id" :value="item.facilityNo">
                  {{ item.facilityName | formatFacilityName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="关联村庄" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-model="model.terminalId" placeholder="关联农污终端检索选择" type="number"></a-input> -->
              <a-select
                v-model="model.villageId"
                show-search
                allowClear
                placeholder="请选择"
                :default-active-first-option="false"
                :show-arrow="false"
                :not-found-content="null"
                option-filter-prop="children"
              >
                <!-- 显示村庄名称+编号 -->
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="item in villageList" :key="item.value" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="进出口" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="model.impExp">
                <a-radio :value="1"> 进水口</a-radio>
                <a-radio :value="2"> 出水口</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="归属状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="model.equBelong">
                <a-radio :value="2"> 售卖</a-radio>
                <a-radio :value="1"> 租赁</a-radio>
                <a-radio :value="3"> 自有</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="阈值设置类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <j-dict-select-tag ct-tag type="list" v-model="operatorType" dictCode="ps_threshold_operator" placeholder="请选择阈值操作符" />
            </a-form-model-item>
            <a-form-model-item label="阈值设置" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="operatorType==3">
              <a-input v-model.number="threshold" placeholder="最小阈值" style="width: 45%" type="number"/> -
              <a-input v-model.number="maxThre" placeholder="最大阈值" style="width: 45%" type="number"/>
            </a-form-model-item>
            <a-form-model-item label="阈值设置" :labelCol="labelCol" :wrapperCol="wrapperCol" v-else>
              <a-input v-model.number="threshold" placeholder="请输入" style="width: 100%"/>
            </a-form-model-item>
            <a-form-model-item label="启用设置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="isEffect">
                <a-radio :value="1">开启</a-radio>
                <a-radio :value="0">关闭</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
// import { validateDuplicateValue } from '@/utils/util'
import debounce from 'lodash/debounce'
import { getPointList } from '@api/point'

import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'

export default {
  name: 'EquipmentForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    hasPointFlag: {
      type: Boolean,
      required: true,
    },
  },
  filters: {
    formatFacilityName(type) {
      return filterDictTextByCache('nw_terminal_facility', type)
    },
  },
  data() {
    this.fetchPointsList = debounce(this.fetchPointsList, 800)
    return {
      model: {},
      operatorType:'',
      threshold:'',
      maxThre:null,
      isEffect:'',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      rowLabelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      rowWrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      confirmLoading: false,
      validatorRules: {
        pointArea: [{ required: true, message: '请选择区域！', trigger: 'change' }],
        equName: [{ required: true, message: '请输入设备名称！', trigger: 'change' }],
        equNo: [{ required: true, message: '请输入设备编号！', trigger: 'change' }],
        pointName: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
        pointCode: [{ required: true, message: '点位编号不能为空', trigger: 'blur' }],
        equType: [{ required: true, message: '请选择设备类型！', trigger: 'change' }],
        // pipPointNo: [{ required: true, message: '管点编号不能为空', trigger: 'blur' }],
      },
      url: {
        add: '/paishui/equipment/add',
        edit: '/paishui/equipment/edit',
        queryById: '/paishui/equipment/queryById',
      },
      //点位查询选择字段
      data: [],
      value: '',
      text: '',
      fetching: false,
      terminalList: [], // 农污终端列表
      facilityList: [], // 农污终端关联设施
      villageList:[]
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.getTerminalList()
    this.getVillageList()
  },
  methods: {
    handleTerminalSelected(terminalId) {
      if (terminalId) {
        this.getFacilityListOfTerminal(terminalId)
      } else {
        this.facilityList = []
      }
    },
    async getFacilityListOfTerminal(terminalId) {
      try {
        const res = await getAction(`/equ1/terminalFacility/list`, { terminalId, pageNo: 1, pageSize: 10000 })
        const facilityList = res.result.records || []
        this.facilityList = facilityList
      } catch (error) {
        console.log(error)
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    async getTerminalList() {
      try {
        const res = await getAction(`/terminal/terminal/list`, { pageNo: 1, pageSize: 10000 })
        const terminalList = res.result.records || []
        this.terminalList = terminalList.map((terminal) => ({
          value: terminal.terminalId,
          label: `${terminal.terminalName}(${terminal.terminalId})`,
        }))
      } catch (error) {
        console.log(error)
      }
    },
    async getVillageList() {
      try {
        const res = await getAction(`/ps/village/list`, { pageNo: 1, pageSize: 10000 })
        const villageList = res.result.records || []
        this.villageList = villageList.map((village) => ({
          value: village.id,
          label: `${village.villageName}(${village.id})`,
        }))
      } catch (error) {
        console.log(error)
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    async edit(record) {
      if(record.threshold){
        this.threshold=record.threshold.threshold
        this.operatorType=record.threshold.operatorType
        this.maxThre=record.threshold.maxThre
        this.isEffect=record.threshold.isEffect-0
      }
      if (record.pointCode) {
        const res = await getAction(`/paishui/paishuiPointPos/list?pointNo=${record.pointCode}`)
        const defaultPoint = res.result.records[0]
        this.value = record.pointCode
        this.data = res.result.records
      }
      this.model = Object.assign({}, record)
      this.visible = true
    },
    submitForm() {
      if (!this.model.pointArea) {
        this.$message.success('缺少点位区域字段')
        return
      }

      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          let thresholdId=this.model.threshold?this.model.threshold.id:''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
            if(!this.operatorType){
              this.model.threshold=null
            } else {
              this.model.threshold=Object.assign({}, { operatorType:this.operatorType,
                threshold:this.threshold,maxThre:this.maxThre, isEffect:this.isEffect+'',equNo:this.model.equNo,pipPointNo: this.model.pipPointNo})
            }


          } else {
            httpurl += this.url.edit
            method = 'post'
            if(!this.operatorType){
              this.model.threshold=null
            } else {
              this.model.threshold=Object.assign({}, { operatorType:this.operatorType,
                threshold:this.threshold,maxThre:this.maxThre, isEffect:this.isEffect+'',equNo:this.model.equNo,pipPointNo: this.model.pipPointNo,
                id:thresholdId
              })
            }

          }
          const { terminalId } = this.model
          const { villageId } = this.model
          const params = { ...this.model, terminalId: terminalId ? terminalId : '',villageId: villageId ? villageId : '' }
          console.log('params', params)
          httpAction(httpurl, params, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    // 查询关联点位列表
    fetchPointsList(value) {
      this.data = []
      this.fetching = true
      if (value == undefined) value = ''
      getAction(`/paishui/paishuiPointPos/list?pointName=*${value}*`).then((res) => {
        this.data = res.result.records
      })
    },
    /*
     * 选中 option，或 input 的 value 变化时
     * */
    handleChange(value, option) {
      const selectPoint = this.data.find((item) => value == item.pointNo)
      // console.log('selectPoint', selectPoint)
      this.model.pointName = selectPoint.pointName
      this.model.pointCode = selectPoint.pointNo
      this.getPointList(selectPoint.pointNo)
      Object.assign(this, {
        value,
        data: [selectPoint],
        fetching: false,
      })
    },
    // 拿到点位编号获取管点编号
    async getPointList(value) {
      const res = await getPointList({ associationPosPointNo: value })
      this.model.pipPointNo = res.result.records[0].pipNo
      this.model.pointArea = res.result.records[0].areaId
    },
  },
}
</script>
